<template>
  <base-breadcrumb
    :title="titleName"
    :breadcrumb="!isAudit"
  >
    <a-spin :spinning="uploadLoading">
      <a-card :bordered="false">
        <title-name
          v-if="type=='edit'"
          title="编辑设计需求申请"
        />
        <title-name
          v-if="type=='view'"
          title="查看设计需求申请"
        />
        <title-name
          v-if="type=='add'"
          title="新增设计需求申请"
        />
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
          :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
        >
          <a-row>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="设计需求类型"
                prop="designDemandTypeId"
              >
                <a-select
                  v-model="form.designDemandTypeId"
                  :get-popup-container="getPopupContainer"
                  placeholder="请选择"
                  :disabled="type=='view' || type=='approve'"
                >
                  <a-spin
                    v-if="loading"
                    slot="notFoundContent"
                    size="small"
                  />
                  <a-select-option
                    v-for="item in typeList"
                    :key="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="设计需求名称"
                prop="designDemandName"
              >
                <BaseInput
                  v-model="form.designDemandName"
                  :disabled="type=='view' || type=='approve'"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="期望回复时间"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="expectRecoveryTime"
              >
                <a-date-picker
                  v-model="form.expectRecoveryTime"
                  style="width: 100%"
                  :disabled="type == 'view' || type == 'approve'"
                  placeholder="请选择日期"
                  @change="onChangeTime"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- 项目部 -->
          <a-row>
            <a-col
              v-if="projectLevel"
              :span="16"
            >
              <a-form-model-item
                label="所属单位"
                :label-col="{lg: {span: 6}, sm: {span:6}}"
                :wrapper-col="{lg: {span: 18}, sm: {span: 18} }"
                prop="projectId"
              >
                <org-tree-select
                  v-model="form.projectId"
                  is-auto-select-first
                  is-need-auth
                  check-strictly
                  :disabled="type=='view'"
                  @select="selectOrg"
                />
              </a-form-model-item>
            </a-col>
            <!--            <a-col-->
            <!--              v-if="projectLevel"-->
            <!--              :md="8"-->
            <!--              :sm="8"-->
            <!--            >-->
            <!--              <a-form-model-item-->
            <!--                label="所属单位"-->
            <!--                :label-col="{lg: {span: 6}, sm: {span:6}}"-->
            <!--                :wrapper-col="{lg: {span: 18}, sm: {span: 18} }"-->
            <!--                prop="branchId"-->
            <!--              >-->
            <!--                <a-select-->
            <!--                  v-model="form.branchId"-->
            <!--                  :get-popup-container="getPopupContainer"-->
            <!--                  placeholder="请选择"-->
            <!--                  :disabled="type=='view'"-->
            <!--                  @change="changeCompany(form.branchId)"-->
            <!--                >-->
            <!--                  <a-spin-->
            <!--                    v-if="loading"-->
            <!--                    slot="notFoundContent"-->
            <!--                    size="small"-->
            <!--                  />-->
            <!--                  <a-select-option-->
            <!--                    v-for="item in branchCompanyLists"-->
            <!--                    :key="item.orgId"-->
            <!--                  >-->
            <!--                    {{ item.orgName }}-->
            <!--                  </a-select-option>-->
            <!--                </a-select>-->
            <!--              </a-form-model-item>-->
            <!--            </a-col>-->
            <!--            <a-col-->
            <!--              v-if="projectLevel"-->
            <!--              :md="8"-->
            <!--              :sm="8"-->
            <!--            >-->
            <!--              <a-form-model-item-->
            <!--                label="项目名称"-->
            <!--                :label-col="{lg: {span: 6}, sm: {span:6}}"-->
            <!--                :wrapper-col="{lg: {span: 18}, sm: {span: 18} }"-->
            <!--                prop="projectId"-->
            <!--              >-->
            <!--                <a-select-->
            <!--                  v-model="form.projectId"-->
            <!--                  :get-popup-container="getPopupContainer"-->
            <!--                  placeholder="请选择"-->
            <!--                  :disabled="type=='view'"-->
            <!--                  @change="changeProject"-->
            <!--                >-->
            <!--                  <a-spin-->
            <!--                    v-if="loading"-->
            <!--                    slot="notFoundContent"-->
            <!--                    size="small"-->
            <!--                  />-->
            <!--                  <a-select-option-->
            <!--                    v-for="item in currentProjectList"-->
            <!--                    :key="item.projectId"-->
            <!--                  >-->
            <!--                    {{ item.projectName }}-->
            <!--                  </a-select-option>-->
            <!--                </a-select>-->
            <!--              </a-form-model-item>-->
            <!--            </a-col>-->
            <a-col
              v-if="projectLevel"
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="项目编号"
                prop="projectNum"
              >
                <BaseInput
                  v-model="form.projectNum"
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col
              v-if="projectLevel"
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="项目设计管理类别"
                prop="designType"
              >
                <BaseInput
                  v-model="form.designType"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col
              v-if="projectLevel"
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="提出部门"
                prop="proposeDeptId"
              >
                <a-select
                  v-model="form.proposeDeptId"
                  :get-popup-container="getPopupContainer"
                  placeholder="请选择"
                  :disabled="type=='view' || type=='approve'"
                  @focus="getDept"
                >
                  <a-spin
                    v-if="loading"
                    slot="notFoundContent"
                    size="small"
                  />
                  <a-select-option
                    v-for="item in deptList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col
              v-if="projectLevel"
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="提出人"
                prop="proposePersonId"
              >
                <BaseInput
                  v-if="type=='view' || type=='approve'"
                  v-model="form.proposePersonName"
                  disabled
                />
                <a-select
                  v-else
                  v-model="form.proposePersonId"
                  :get-popup-container="getPopupContainer"
                  placeholder="请选择"
                  :disabled="type=='view' || type=='approve'"
                >
                  <a-spin
                    v-if="loading"
                    slot="notFoundContent"
                    size="small"
                  />
                  <a-select-option
                    v-for="item in memberList"
                    :key="item.employeeId"
                    :value="item.employeeId"
                  >
                    {{ item.employeeName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <!-- 公司角色 -->
            <a-col
              v-if="!projectLevel && !branchLevel"
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="所属单位"
                prop="branchId"
              >
                <a-select
                  v-model="form.branchId"
                  :get-popup-container="getPopupContainer"
                  placeholder="请选择"
                  :disabled="type=='view'"
                  @change="changeCompanyList(form.branchId)"
                >
                  <a-spin
                    v-if="loading"
                    slot="notFoundContent"
                    size="small"
                  />
                  <a-select-option
                    v-for="item in companyLists"
                    :key="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 分公司角色 -->
            <a-col
              v-if="!projectLevel && !companyLevel"
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="所属单位"
                prop="branchId"
              >
                <a-select
                  v-model="form.branchId"
                  :get-popup-container="getPopupContainer"
                  placeholder="请选择"
                  :disabled="type=='view'"
                  @change="changeCompanyList(form.branchId)"
                >
                  <a-spin
                    v-if="loading"
                    slot="notFoundContent"
                    size="small"
                  />
                  <a-select-option
                    v-for="item in branchLists"
                    :key="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 公司、分公司 -->
            <a-col
              v-if="!projectLevel"
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="提出部门"
                prop="proposeDept"
              >
                <BaseInput
                  v-model="form.proposeDept"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col
              v-if="!projectLevel"
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="提出人"
                prop="proposePersonName"
              >
                <BaseInput
                  v-model="form.proposePersonName"
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item label="创建人">
                <BaseInput
                  v-model="form.creatorName"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item label="创建时间">
                <BaseInput
                  v-model="form.createTime"
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                label="需求概述"
                prop="information"
              >
                <editor-bar
                  v-model="form.information"
                  :disabled="type=='view' || type=='approve'"
                  :is-clear="isClear"
                  @change="change"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <title-name title="上传相关附件" />
        <div>
          <a-row>
            <a-col
              :md="24"
              :sm="19"
            >
              <div class="table-operator">
                <a-upload
                  v-if="type !='view'"
                  name="file"
                  multiple
                  :disabled="spinning"
                  :show-upload-list="false"
                  :before-upload="beforeUpload"
                  @change="handleChanges"
                >
                  <a-button
                    :disabled="spinning"
                    type="primary"
                    style="margin-bottom: 20px;"
                  >
                    <a-icon
                      :type="spinning ? 'loading' : 'upload'"
                      style="font-size: 1.2rem"
                    />
                    上传
                  </a-button>
                </a-upload>
                <a-button
                  v-if="type !='view'"
                  type=""
                  style="margin-bottom: 20px;margin-left: 20px"
                  @click="deleteExteriorFile()"
                >
                  <a-icon style="font-size: 1.2rem" />
                  删除
                </a-button>

                <a-table
                  bordered
                  row-key="id"
                  :columns="columnAssment"
                  :data-source="dataAssement"
                  :row-selection="type !='view'?rowSelection:null"
                >
                  <span
                    slot="serial"
                    slot-scope="text, record, index"
                  >{{ index + 1 }}</span><span
                    slot="action"
                    slot-scope="text, record, index"
                  >
                    <a
                      :href="'/api/ycloud-file-center/oper/download?access_token='+token+'&fileId='+record.fileId"
                      target="_parent"
                    >导出</a>
                    <a-divider type="vertical" />
                    <a
                      href="javascript:"
                      @click="$filePreview(record)"
                    >预览</a>
                  </span>
                </a-table>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-card>

      <a-card v-if="statusCode == '4'">
        <title-name title="设计支持" />
        <a-form-model
          ref="ruleForm"
          :model="form"
          :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
          :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
        >
          <a-row>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="支持人员"
                prop="designDemandName"
              >
                <BaseInput
                  v-model="form.supportName"
                  :disabled="type=='view' || type=='approve'"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item
                label="支持时间"
                prop="designDemandName"
              >
                <BaseInput
                  v-model="form.supportDate"
                  :disabled="type=='view' || type=='approve'"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-table
            bordered
            row-key="id"
            :columns="columnAssment"
            :data-source="form.reportFileIdsInfo"
          >
            <span
              slot="serial"
              slot-scope="text, record, index"
            >{{ index + 1 }}</span><span
              slot="action"
              slot-scope="text, record, index"
            >
              <a
                :href="'/api/ycloud-file-center/oper/download?access_token='+token+'&fileId='+record.fileId"
                target="_parent"
              >导出</a>
            </span>
          </a-table>
        </a-form-model>
      </a-card>

      <div
        v-if="!isAudit"
        class="footer page-btn-right-top"
      >
        <a-button
          v-if="type != 'view'"
          :loading="loadings"
          type="primary"
          @click="saveDraft()"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="type != 'view'"
          :loading="loadingSubmit"
          type="primary"
          @click="saveSubmit()"
        >
          提交
        </a-button>
        <a-button
          type="default"
          @click="goBack"
        >
          关闭
        </a-button>
      </div>
    </a-spin>
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
  </base-breadcrumb>
</template>

<script>
import Vue from 'vue'
import { STable, Ellipsis } from '@/components'
import EditorBar from '@/components/Editor/editor'
import { addBasic, getProjectType } from '@/api/design/plotsPlan'
import { getScoreList, addScoreList, editScoreList } from '@/api/evaluate'
import { addDemandList, getDetails, editDemandList, deleteFiles } from '@/api/design/demand'
import { getTypes, getUsersDetail, getOrgUsers, getOrganizeUserList, getDept } from '@/api/commons'
import { themeChoose } from '@/mixin/mixin'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import { getProjectsDel } from '@/api/project/projects'
import { uploadFile, deleteUploadFile } from '@/api'
import { getCompany, getCurrentUserBranchCom, getAuditProject } from '@/api/themeChoose/themeChoose'
import debounce from 'lodash/debounce'

const columnAssment = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: '5%',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '附件名称',
    dataIndex: 'fileName',
    width: '35%'
  },
  {
    title: '附件格式',
    dataIndex: 'suffixName',
    width: '35%'
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  mixins: [themeChoose],
  props: { isAudit: { type: Boolean, default: false } },
  components: {
    STable,
    EditorBar,
    SelectSubCompany,
    SelectProject
  },
  data() {
    return {
      companyLists: [],
      statusCode: '',
      loading: false,
      uploadLoading:false,
      loadings: false,
      loadingSubmit: false,
      titleName: '',
      columnAssment,
      dataAssement: [],
      uploadFile: {},
      deleteObj: {},
      token: '',
      fileFileds: null,
      fileIds: [],
      dataSource: [],
      fileArrysDataList: [],
      forms: {},
      projectManagers: [],

      // 查询参数
      queryParam: {},

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getScoreList(requestParameters)
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: '',
      selectedRows: '',

      confirmLoading: false,
      id: '',
      // 附件上传
      listUrl: '',
      deleteUrl: '',
      uploadArrys: [],
      uploadList: ' ',
      memberList: [],
      businessId: ' ',
      businessCode: 'PM24',
      reqMethod: 'post',
      name: '',
      typeList: [],
      deptList: [],
      branchLists: [],
      deptId: '',
      proposePerson: {},
      designType: [],
      test: '',
      isClear: false,
      information: '',
      editorContent: '',
      status: '',
      projectLevel: false,//是否为项目部层级
      branchLevel: false,//是否为分公司层级
      companyLevel: false,//是否为公司层级
      pageType: '',
      jobsList: [],
      currentProjectList: [],
      userId: '',
      branchName: '',
      user: '',
      type: '',
      disabled: false,
      form: {
        branchId: '',
        proposeDept: '',
        createTime: this.getNowTime().slice(0, 10),
        creatorName: ''
      },
      visible: false,
      branchCompanyLists: [],
      rules: {
        designDemandTypeId: [{ required: true, message: '请选择设计需求类型', trigger: 'change' }],
        designDemandName: [{ required: true, message: '请输入设计需求名称', trigger: 'blur' }],
        branchId: [{ required: true, message: '请选择单位名称', trigger: 'change' }],
        expectRecoveryTime: [{ required: true, message: '请选择期望回复时间', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        proposeDeptId: [{ required: true, message: '请选择提出部门', trigger: 'change' }],
        proposePersonId: [{ required: true, message: '请选择提出人', trigger: 'change' }],
        information: [{ required: true, message: '请输入需求概述', trigger: 'blur' }]
      }
    }
  },
  watch: {
    isAudit: {
      handler() {
        if (this.isAudit) {
          this.type = 'view'
        }
      }
    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
          let fileFileds = []
          let fileIds = []
          selectedRows.forEach(function(obj, i) {
            fileFileds.push(obj.fileId)
            fileIds.push(obj.commonId)
          })
          this.fileFileds = fileFileds.join(',')   // 删除公共附件
          this.fileIds = fileIds                   // 有业务id 删除附件
        }
      }
    }
  },
 async created() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.userId = JSON.parse(sessionStorage.getItem('ycloud-user_info')).id
    this.form.creatorName = JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.name
    this.id = this.$route.query.id
    this.statusCode = this.$route.query.statusCode
    this.type = this.$route.query.type
    if (this.type == 'add') {
      this.titleName = '新增设计需求申请'
    } else if (this.type == 'edit') {
      this.titleName = '编辑设计需求申请'
    }

    this.getDetails()
    this.getUsersDetail()

    if (this.type == 'approve') {
      this.getProjectManager()
    }
    // this.getjobsList()
    // this.getScoreList()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('design_demand_apllication')
  },
  methods: {
    selectOrg(val) {
      if(val.length>1) {
        this.changeProject(this.form.projectId)
      }
    },
    // projectLevel:false,//是否为项目部层级
    // branchLevel:false,//是否为分公司层级
    // companyLevel:false,//是否为公司层级
    getTypes() {
      let code = ''
      if (this.projectLevel) {
        code = 'xmb'
      } else {
        code = 'gs'
      }
      getTypes({ type: '22', code: code }).then(res => {
        this.typeList = res.data
      })
    },
    onChangeTime(val) {
      this.form.expectRecoveryTime = val.format('YYYY-MM-DD')
      if (new Date(this.form.expectRecoveryTime).getTime() < new Date(this.form.createTime).getTime()) {
        this.$message.error('期望回复时间不能早于申请创建时间')
        this.$set(this.form, 'expectRecoveryTime', '')
      }
    },
    changeCompanyList(value) {

    },
    getCurrentUserBranchCom() {
      let that = this
      getCurrentUserBranchCom({ tagCodes: ['BC'] }).then(res => {
        that.branchCompanyLists = res.data
        // 根据所选岗位筛选出单位
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        that.form = {
          ...that.form,
          branchId: userInfo?.currentPost?.orgId ?? that.branchCompanyLists[0]?.orgId ?? that.form.branchId
        }
        if (that.projectLevel) {
          // 项目部的人，筛选出所选岗位对应的单位列表
          that.branchCompanyLists = that.branchCompanyLists.filter(item => {
            return item.orgId === userInfo?.currentPost?.orgId
          })
          getAuditProject({ branchComIds: [that.form.branchId], auditStatus: 2 }).then(res => {
            that.currentProjectList = res.data
            that.loading = false
            that.$set(that.form, 'projectId', that.currentProjectList[0]?.projectId)
            that.$set(that.form, 'projectNum', that.currentProjectList[0]?.projectNum)
            that.$set(that.form, 'designType', that.currentProjectList[0]?.designTypeName)
            that.$set(that.form, 'designTypeId', that.currentProjectList[0]?.designTypeId)
            that.deptId = that.currentProjectList[0]?.projectDeptId
            getOrganizeUserList({ id: that.form.projectId }).then(res => {
              that.memberList = res.data
            })
          })
        }
      })
    },

    changeCompany(val) {
      this.$set(this.form, 'projectId', '')
      this.$set(this.form, 'projectNum', '')
      this.$set(this.form, 'designType', '')
      this.$set(this.form, 'designTypeId', '')
      this.$set(this.form, 'proposePersonId', '')
      this.$set(this.form, 'proposeDeptId', '')
      getAuditProject({ branchComIds: [val], auditStatus: 2 }).then(res => {
        this.currentProjectList = res.data
        this.loading = false
        if (this.currentProjectList.length) {
          this.$set(this.form, 'projectId', this.currentProjectList[0].projectId)
          this.$set(this.form, 'projectNum', this.currentProjectList[0].projectNum)
          this.$set(this.form, 'designType', this.currentProjectList[0].designTypeName)
          this.$set(this.form, 'designTypeId', this.currentProjectList[0].designTypeId)
        }
        this.changeProject(this.form.projectId)
      })
    },
    getPopupContainer(triggerNode) {
      return triggerNode.parentNode
    },
    fileArrysData(val) {
      this.fileArrysDataList = val
    },
    // 上传

    beforeUpload(info) {
      // this.uploadFile = info
      return false
    },

    handleChanges(info) {
      let pass = true
      const { file } = info
      if (file.size / 1024 / 1024 > 500) {
        // 附件大小校验
        // 限制文件大小为500M
        this.sizeDebounce()
        pass = false
      }
      if (pass) {
        this.files.push(file)
        this.fileChange()
      }
    },
    /**
     * @description: 判断及操作上传文件队列
     * @return {void}
     */
    async handleUploadFun() {
      let pass = true
      if (pass && this.dataAssement.length + this.files.length > this.count) {
        pass = false
        this.$message.error(`最多上传${this.count}个文件！`)
        this.files = this.files.slice(0, this.count - this.dataAssement.length)
      }
      if (pass && this.files.length > this.num) {
        this.$message.error(`一次最多上传${this.num}个文件！`)
        this.files = this.files.slice(0, this.num)
      }
      this.spinning = true
      // 防止上传错误一直loading
      try {
        for (let i = 0; i < this.files.length; i++) {
          await this.uploadFun(this.files[i])
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.files = []
        this.spinning = false
      }
    },
    /**
     * @description: 上传函数拆分
     * @param {FormData} data
     * @return {void}
     */
    uploadFun(info) {
      return new Promise(async (resolve, reject) => {
        let that = this
        const data = new FormData()
        data.append('file', info)
        data.append('businessCode', that.businessCode)
        let arr = []
        uploadFile(data)
          .then((res) => {
            if (res.code === 200) {
              arr.push(res.data)
              if (that.dataAssement == null) {
                that.dataAssement = arr
              } else {
                that.dataAssement = that.dataAssement.concat(arr)
              }
              let commonIds = []
              that.dataAssement.forEach &&
                that.dataAssement.forEach((item) => {
                  commonIds.push(item.commonId)
                })
              that.form.designFileIdsInfo = that.dataAssement
              that.form.designFileIds = commonIds
              resolve()
            }
            this.uploadLoading = false
          })
          .catch((error) => {
            console.log(error)
            this.$message.warning('上传失败')
            reject(error)
          })
      })
    },
    deleteExteriorFile() {
      let that = this
      if (that.selectedRowKeys.length == 0) {
        that.$message.error('请先选中需要删除的附件！')
        return
      }
      if (that.id) {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            that.uploadLoading = true
            deleteFiles({ businessId: that.id, fileList: that.fileIds }).then((res) => {
              if (res.code == 200 || res.data.code == 200) {
                that.$message.success('删除附件成功！')
                that.uploadLoading = false
                that.selectedRowKeys = []
                that.selectedRows = []
                that.getDetails()
              }
            })
          },
          onCancel() {
            that.uploadLoading = false
          }
        })
      } else {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            that.uploadLoading = true
            deleteUploadFile({ fileIds: that.fileFileds }).then((res) => {
              if (res.code == '0' || res.data.code == '0') {
                that.$message.success('删除附件成功！')
                that.uploadLoading = false
                let data = that.dataAssement
                let selectDatas = that.fileIds
                that.dataAssement = data.filter((item) => {
                  return !selectDatas.includes(item.commonId)
                })
                that.selectedRowKeys = []
                that.selectedRows = []
              }
            })
          },
          onCancel() {
            that.uploadLoading = false
          }
        })
      }
    },

    onSelectChanges(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      let fileFileds = []
      let fileIds = []
      selectedRows.forEach(function (obj, i) {
        fileFileds.push(obj.commonId) //
        fileIds.push(obj.fileId)
      })
      this.fileFileds = fileFileds.join(',')
      this.fileIds = fileIds
    },
    getDept() {
      if (this.deptId) {
        getDept({ id: this.deptId }).then((res) => {
          this.deptList = res.data
          this.loading = false
        })
      }
    },
    changeProject(value) {
      this.$set(this.form, 'proposeDeptId', '')
      this.$set(this.form, 'proposePersonId', '')
      this.loading = true
      this.deptList = []
      this.memberList = []
      if (!value) {
        this.deptId = ''
        this.loading = false
        return
      }
      getProjectsDel({ projectId: value }).then((res) => {
        this.form.designType = res.data.designName
        this.form.projectNum = res.data.projectNum
        this.form.designId = res.data.designId
        this.deptId = res.data.projectDeptOrgId
        this.getDept()
      })
      getOrganizeUserList({ id: value }).then((res) => {
        this.memberList = res.data
        this.loading = false
      })
    },
    getProjectManager() {
      getOrgUsers(this.queryData).then((res) => {
        this.projectManagers = res.data
      })
    },
    getDetails() {
      if (this.id) {
        getDetails({ id: this.id }).then((res) => {
          this.form = res.data
          this.dataAssement = res.data.designFileIdsInfo
          if (!this.dataAssement) {
            this.dataAssement = []
          }
          if (this.projectLevel) {
            getOrganizeUserList({ id: this.form.projectId }).then((res) => {
              this.memberList = res.data
            })
          }
        })
        getDept({ id: this.form.projectDeptOrgId }).then((res) => {
          this.deptList = res.data
        })
      }
    },
    getUsersDetail() {
      let that = this
      getUsersDetail({ userId: that.userId }).then((res) => {
        let obj = JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost
        that.branchLevel = obj.code == 'BC' //分公司级
        that.branchLists = [obj]
        that.companyLevel = obj.code == 'CO' //公司级
        that.companyLists = [{ ...obj, id: obj.orgId }]
        that.projectLevel = obj.code == 'PD' //项目级

        console.log('当前数据6688：', that.projectLevel)
        that.getTypes()
        that.getCurrentUserBranchCom()
        if (that.branchLevel && !that.projectLevel) {
          // 赋值为登录所选岗位的部门id及name
          that.form.proposeDept = obj?.deptName ?? ''
          that.form.proposeDeptId = obj?.deptId ?? ''
          that.form.proposePersonName = res.data.name
          that.form.proposePersonId = res.data.id
          this.$set(this.form, 'branchName', that.branchLists[0].name)
          this.$set(this.form, 'branchId', that.branchLists[0].id)
        } else if (that.companyLevel && !that.branchLevel && !that.projectLevel) {
          this.$set(this.form, 'branchName', that.companyLists[0].name)
          this.$set(this.form, 'branchId', that.companyLists[0].id)
          that.form.proposePersonName = res.data.name
          that.form.proposePersonId = res.data.id
          // 赋值为登录所选岗位的部门id及name
          that.form.proposeDept = obj?.deptName ?? ''
          that.form.proposeDeptId = obj?.deptId ?? ''
        }
      })
    },
    selectProject(value) {
      let arr = []
      arr.push(value)
      getProjectType({ projectIds: arr }).then((res) => {
        this.form.projectNum = res.data[0].projectNumber
        this.form.designType = res.data[0].designTypeName
        this.form.designTypeId = res.data[0].designTypeId
        // if(this.form.designType=="B类"){
        //   this.tableData = this.tableData1
        // }else if(this.form.designType=="C类"){
        //   this.tableData = this.tableData2
        // }
      })
    },

    getScoreList() {
      getScoreList().then((res) => {
        this.loadData = res.data
      })
    },
    saveDraft() {
      this.form.proposePersonName = this.proposePerson.label
      let arr1 = []
      let arr2 = []
      if (this.projectLevel) {
        if (this.form.branchId) {
          arr1 = this.branchCompanyLists.filter((item) => item.orgId == this.form.branchId)
          if (arr1) {
            this.form.branchName = arr1[0].orgName
          }
        }

        if (this.form.proposeDeptId) {
          arr2 = this.deptList.filter((item) => item.id == this.form.proposeDeptId)
          if (arr2) {
            this.form.proposeDept = arr2[0].name
          }
        }
      }

      this.$refs.ruleForm.validate((valid, value) => {
        if (valid) {
          if (this.form.designFileIdsInfo) {
            let arr = []
            this.form.designFileIdsInfo.forEach((item) => {
              arr.push(item.commonId)
            })
            this.form.designFileIds = arr
          }
          this.form.statusCode = '0'
          if (this.id) {
            this.loadings = true
            editDemandList(this.form).then((res) => {
              this.loadings = false
              this.$router.push('/project/design/demand')
              if (res.code == 200 || res.data.code == 200) {
                this.$message.success('保存草稿成功')
              }
            })
          } else {
            this.loadings = true
            addDemandList(this.form).then((res) => {
              this.loadings = false
              if (res.code == 200 || res.data.code == 200) {
                this.$router.push('/project/design/demand')
                this.$message.success('保存草稿成功')
              }
            })
          }
        }else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    saveSubmit() {
       this.setProcessConfig = null;
      // this.form.proposeDept=this.proposeDept.label
      // this.form.proposeDeptId = this.proposeDept.key
      this.form.proposePersonName = this.proposePerson.label
      let arr1 = []
      let arr2 = []
      if (this.projectLevel) {
        if (this.form.branchId) {
          arr1 = this.branchCompanyLists.filter((item) => item.orgId == this.form.branchId)
          if (arr1) {
            this.form.branchName = arr1[0].orgName
          }
        }
        if (this.form.proposeDeptId) {
          arr2 = this.deptList.filter((item) => item.id == this.form.proposeDeptId)
          if (arr2) {
            this.form.proposeDept = arr2[0].name
          }
        }
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.form.designFileIdsInfo) {
            let arr = []
            this.form.designFileIdsInfo.forEach((item) => {
              arr.push(item.commonId)
            })
            this.form.designFileIds = arr
          }
          this.form.statusCode = '1'
          this.submitApprovalConfirm(this.processConfig,(flag)=>{
            if(!flag) {
              this.loadingSubmit = false
              return
            }
          if (this.id) {
            this.loadingSubmit = true
            editDemandList(this.form).then((res) => {
              this.loadingSubmit = false
              if (res.code == 200 || res.data.code == 200) {
                this.$message.success('提交成功')
                //提交时，返回id
                this.businessId = res.data;
                this.setProcessConfig = this.processConfig;
              }
            })
          } else {
            this.loadingSubmit = true
            addDemandList(this.form).then((res) => {
              this.loadingSubmit = false
              if (res.code == 200 || res.data.code == 200) {
                this.$message.success('提交成功')
                //提交时，返回id
                this.businessId = res.data;
                this.setProcessConfig = this.processConfig;
              }
            })
          }
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    goBack() {
      this.$multiTab.close(this.$route.fullpath)
    },
    change(value) {
      this.$refs.ruleForm && this.$refs.ruleForm.validateField('information')
      // if(value.length>40){
      //   value = value.subString(0,40)
      // }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    search() {
      this.$refs.table.refresh(true)
    },
    goAdd() {
      this.visible = true
    },
    handleSub(record, type) {
      this.visible = true
      this.type = type
      this.form = record
    },
    handleEdit(record) {
      this.visible = true
      this.form = record
    },
    handleOk() {
      this.visible = false
      if (this.form.id) {
        editScoreList(this.form).then((res) => {
          if (res.code == '200') {
            this.$message.success('编辑成功')
          }
        })
      } else {
        addScoreList(this.form).then((res) => {
          if (res.code == '200') {
            this.$message.success('新增成功')
          }
          this.$refs.table.refresh(true)
        })
      }
    },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>

<style scoped>
/deep/ .ant-form-item .ant-form-item-control-wrapper {
  width: calc(100% - 135px) !important;
}

.input {
  width: 100%;
}

.footer {
  float: right;
  margin-right: 10px;
}

.footer button {
  margin-left: 10px;
}
</style>
